//app.js
import {
  util,
  api,
  storage
} from 'js/util'
import {
  router
} from 'js/router'
import {
  config,
  domain,
  account,
  category,
  area
} from "js/modules/gloab";
import { getFuzzyLocation } from './js/authSetting';
import { getStorageSync, hideTabbar, setStorageSync } from './js/compatible';
import pageNotFound from './js/pageNotFound';
import { isEmpty, jsonToQuery } from './js/newUtil';
var amapFile = require('js/common/amap-wx.js');
import { cityFormat } from './js/common/amap-format'
App({
  onLaunch: function(options) {
    console.log('app-options',options);
    //隐藏原生底部导航
    hideTabbar()
    //读取ext.json内容并获取设备信息，以及初始化底部导航
    this.initGlobal(options);
    //检查程序是否有更新
    this.checkUpdate();
    //自动登录
    this.autoLogin();
  },
  onShow (e) {
    console.log('app show', e)
    this.globalData.appShowData = e
  },
  /**
   * 错误日志记录
   */
  onError: function(err) { 
    let entity = storage.get("LoginSessionKey") || {
      manager: {}
    };
    let data = {
      Proprietor: this.dns.proprietor,
      ProprietorId: this.dns.proprietorId,
      FKFlag: this.dns.proprietor,
      FKId: this.dns.proprietorId,
      FKWay: this.dns.fkWay,
      LoginFKFlag: entity.fkFlag,
      LoginFKId: entity.fkId,
      LoginManagerId: entity.manager.ManagerId,
      PageKey: "minpro_error_page",
    }
    util.post_api_err({
      errMsg: err
    }, data);
  },
  /**
   * 
   * @param {*} e 参数
   * @param {*} e.path 不存在的页面的路径
   * @param {*} e.query 不存在的页面的query
   */
  onPageNotFound (e) {
    // 当页面不存在，并且只有一个页面时，重定向到首页
    console.log('page not Found:', e)
    const {
      path,
      query
    } = e
    let page = getCurrentPages()
    if (!page) {
      page = []
    }
    if (pageNotFound[path]) {
      let data = jsonToQuery(query)
      wx.redirectTo({
        url: `${pageNotFound[path]}?${data}`,
      })
    } else if (page.length < 2) {
      wx.reLaunch({
        url: '/pages/index',
        fail (err) {
          console.log(err)
        }
      })
    }
  },
  initGlobal:function(options = {}){
    let _this = this
    //获取ext中配置的自定义字段
    let ext = wx.getExtConfigSync();
    if (ext) {
      api.title = ext.name || "快马数字";
      if (ext.attr) {
        api.host = "https://" + ext.attr.host;    //正式
        this.set_app_config(ext.attr);
      }
    }
    // 获取缓存的全局文字缩放比例
    let fontSizeScale = getStorageSync('fontSizeScale')
    this.globalData.fontSizeScale = fontSizeScale || 1
    //获取手机型号
    wx.getSystemInfo({
      success: res => {
        let modelmes = res.model;
        _this.globalData.isIphoneX = false
        let iphoneArr = ['iPhone X','iPhone 11','iPhone 11 Pro Max','iPhone XR','iPhone 12','iPhone 12 Pro Max','iPhone 12 Pro','iPhone 12 mini','iPhone 13','iPhone 13 Pro','iPhone 13 Pro Max','iPhone 13 mini','iPhone 14','iPhone 14 Plus','iPhone 14 Pro','iPhone 14 Pro Max']
        iphoneArr.forEach(function (item) {
          if (modelmes.search(item) != -1) {
            _this.globalData.isIphoneX = true
          }
        })    
      }
    })
    //重置底部导航默认选中
    setStorageSync('tabindex', -1)
    var tabbar = storage.get("tabBar");
    if (tabbar && tabbar.length > 0) {
      this.globalData.tabBar.list = tabbar;
      this.globalData.tabBar.originList = storage.get('originTabbar')
    }
    //获取缓存
    var dns = storage.get("dns");
    if (dns) {
      this.dns = dns;
      api.projectDir = dns.projectDir || '';
    }
    //存储app onlaunch时的数据，如场景值等
    this.globalData.appLaunchData = options
  },
  checkUpdate:function(){
    //强制更新
    const updateManager = wx.getUpdateManager()
    if(updateManager!=null){
      //检查版本更新
      updateManager.onUpdateReady(function() {
        wx.showModal({
          title: '更新提示',
          content: '新版本已经准备好，是否重启应用？',
          success: function(res) {
            if (res.confirm) {
              // 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
              // account.loginOut();
              updateManager.applyUpdate()
            }
          }
        })
      });
    }
  },
  autoLogin: function(){
    if (this.dns && this.dns.proprietorId > 0) {
      //获取必要信息
      this.loadNeedInfo();
    }else{
      //获取域名信息
      this.get_domain_info();
    }
  },
  /**
   * 获取域名信息
   */
  get_domain_info: function(index=0) {
    let that = this;
    wx.clearStorageSync();
    wx.clearStorage();
    domain.getDomain((res)=> {
      let isContinue=true;
      if (res && res.Success) {
        let item = res.Content;
        if (item) {
          isContinue=false;
          that.set_app_config(item);
          that.loadNeedInfo();
        }
      }
      if(isContinue)
      {
        //小于3次继续请求   
        index=index+1;     
        if(index<3){
            this.get_domain_info(index);
        }
        else if(res.Code ==4002){
          util.alert("请将手机时间调整为当前北京时间后再使用!");
        }
        else{
          util.alert("请联系管理员域名解析不正确!");
        }
        let err=Object.assign({
          errorNums:"第"+index+"次请求域名错误"
        },api);
        this.onError({errMsg:err});
      }
    });
  },
  //设置配置
  set_app_config(config){
    api.domain = config.domain;
    api.imgDomain = "http://" +config.imgDomain;
    api.videoDomain = "http://" +config.videoDomain;
    api.h5Domain = "https://m." + config.domain;
    // api.h5Domain = "http://m." + config.domain;  //开发模式（和H5联调）
    // api.enableOss =config.enableOss;
    api.enableOss =true;
    api.publicVersion = config.publicVersion;
    api.gwDomain="https://" + config.gwDomain;
    if(config.config){
      this.setTitleColor(config.config.TitleColorForMobile);
    }
    this.dns.fkFlag = config.fkFlag;
    this.dns.fkId = config.fkId;
    this.dns.proprietorId = config.fkFlag == 2 && config.fkId > 0 ? config.fkId : 0;
    this.dns.zoneId = config.fkFlag == 3 && config.fkId > 0 ? config.fkId : 0;
      // 如果是开发环境使用以下host地址进行测试
      if (wx.getSystemInfoSync().platform == 'devtools') {
        api.host = api.host.replace("https://","http://");
      }
  },
  setTitleColor(titleColor){
    if (titleColor) {
      let cache = ''
      // 获取缓存的主题颜色
      try {
        cache = getStorageSync('configTitleColor') || ''
      } catch (e) {}
      if (cache) {
        api.titleColor = cache
        titleColor = cache
      } else {
        api.titleColor = titleColor
      }
      wx.setNavigationBarColor({
        backgroundColor: titleColor,
        frontColor: '#ffffff',
      });
    }
  },
  loadNeedInfo(){
    //加载线路
    this.getProprietor();
    //加载配置
    this.getWholesaleConfigs();
    //获取OpenId
    this.getOpenId('');
    //换取上传token
    account.get_upload_token(1,this.dns.proprietorId);
    //加载分类
    category.load(this.dns.proprietorId, this.dns.proprietor, 0);
    //加载地区
    area.load();
  },
  /**获取用户的小程序openid */
  getOpenId(token,callback) {
    console.log("8888888888888")
    wx.login({
      success: res => {
        var param = {
          proprietorId:this.dns.proprietorId,
          fKId:this.dns.fkId,
          fKFlag:this.dns.fkFlag,
          fk_way:this.dns.fkWay, 
          code:res.code,
          token:token||''
        };
        util.post("social.minpro.authorize.info", param, function(res) {
          res = res.data;
          setStorageSync('openid', res.Success&&res.Content?res.Content.openid:0)
          if (callback != undefined && typeof(callback) == "function") {
            callback(res);
          }
        },"3.0");
      },
      fail:res=>{console.log(res)}
    });
  },
  /**
   * 获取配置文件
   * 
   * 
   */
  getProprietor() {
    let that = this;
    config.getProprietor(function (res) {
      if (res.Success && res.Content) {
        let item = res.Content[0] || {};
        if (!isEmpty(item)) {
          let projectDir = item.ProjectDir || '';
          that.dns.fkFlag = item.FKFlag || 2;
          that.dns.fkId = item.FKId || 0;
          that.dns.proprietor = item.Proprietor || 2;
          that.dns.proprietorId = item.ProprietorId || 0;
          that.dns.zoneId = item.FKFlag == 3 && item.FKId > 0 ? item.FKId : 0;
          that.dns.projectDir = projectDir;
          api.projectDir = projectDir;
          api.domain = item.Domain || api.domain;
          storage.put("dns", that.dns);
          storage.put("version", Number(item.SoftwareVersion) || 1);
          // if (projectDir && projectDir != '') {
          //   let domain = api.domain
          //   let index = domain.lastIndexOf('/')
          //   if (!domain.includes(projectDir)) {
          //     if (index == -1) {
          //       domain = `${domain}/${projectDir}`
          //     } else {
          //       let str1 = domain.slice(0, index)
          //       let str2 = domain.slice(index + 1)
          //       domain = `${str1}/${projectDir}/${str2}`
          //     }
          //   }
          //   api.domain = domain;
          // }
        }
      }
    })
  },
  /** 获取本地缓存自动登录 */
  exchangeToken(){
    let role = storage.get("LoginSessionRoleKey");
    let token = storage.get("LoginSessionTokenKey");
    if (role && role.length > 0 && token && token.length > 0) {
      //交换token
      account.exchange_for_token(role, token, function(status, res){
        if (!status && api.isLoginVisit) {
          //自动登录失败且必须要登录访问商城则跳转到登录页面
          wx.redirectTo({
            url: '/pages/account/login/login',
          })
        }
      });
    }
  },
  /**获取网站信息 */
  getWholesaleConfigs(){
    let that = this;
    let { proprietorId, proprietor, fkFlag } = this.dns;
    //获取批发配置
    config.getWholesaleConfigs(proprietorId, proprietor, "Wholesale", (model) => {
      if (proprietor == fkFlag && model) {
        let logo = model.LogoForMobile ? (api.imgDomain + model.LogoForMobile) : "";
        let bg_pic = model.LoginBgPicForMobile ? (api.imgDomain + model.LoginBgPicForMobile + "?x-oss-process=image/resize,m_lfit,w_640") : "";
        api.webSite.logo = logo;
        api.webSite.bgPic = bg_pic;
        api.title = model.SiteName;
        api.isLoginVisit = model.IsVisitMallNeedLogin == true;
        api.addressAssignDepot = model.AddressAssignDepot;
        api.Currency = model.Currency;
        api.amapKey = model.amapAppKey;
        api.CartName = model.CartName || '购物车';
        that.setTitleColor(model.TitleColorForMobile);
        // 缓存主题色，下次直接取这个颜色
        try {
          setStorageSync('configTitleColor', model.TitleColorForMobile)
        } catch (e) {}
      } else {
        api.isLoginVisit = true;   //处理通用下无法显示页面的情况
      }
      //自动登录
      that.exchangeToken();
    }, true);
    
  },
  /**获取当前位置信息 */
  getCurrentLocation(amapKey,callback){
    let that = this;
    try{
      getFuzzyLocation({
        type: 'gcj02', //返回可以用于wx.openLocation的经纬度
        success: function (res) {
          if (!res) return;
          console.log(res,'====getFuzzyLocation====');
          let latitude = res.latitude//维度
          let longitude = res.longitude//经度
          that.getAddressByLocation(amapKey,longitude,latitude,function(status, res){
            if (status) {
              that.globalData.location = res;
            }else{
              if(!amapKey){
                util.tips('很抱歉，无法使用定位，平台尚未启用');
              }
            }
            if (callback && typeof (callback) == "function") {
              callback(that.globalData.location);
            }
          });
        },
        fail:(e)=>{
          console.log('error in getFuzzyLocation:', e)
          if (callback && typeof (callback) == "function") {
            callback(that.globalData.location);
          }
        }
      })
    } catch (e) {
      if (callback && typeof (callback) == "function") {
        callback(that.globalData.location);
      }
      console.log('error in getFuzzyLocation:', e)
    }
  },
  /** 逆地理编码 */
  getAddressByLocation(amapKey,longitude,latitude,callback){
    let myAmapFun = new amapFile.AMapWX({ key: amapKey });
    myAmapFun.getRegeo({ 
      location: '' + longitude + ',' + latitude + '',//location的格式为'经度,纬度'
      success: function (data) {
        console.log(data,'====getLocationAddress====');
        data = cityFormat(data)
        let address = data[0].regeocodeData.addressComponent;
        let { province, city, district, adcode, streetNumber, towncode, township } = address;
        let detailAddress = '';  //详细地址
        //详细地址
        if(streetNumber.street && streetNumber.street!=''){
          if(streetNumber.number && streetNumber.number!=''){
            detailAddress = streetNumber.street+streetNumber.number;
          }else{
            detailAddress = streetNumber.street;
          }
        }
        let resData = {
          adcode: adcode,
          district: district,
          province: province,
          city: city,
          detailAddress: detailAddress,
          lng:longitude,
          lat:latitude,
          towncode: towncode,
          town: township
        }
        if (callback && typeof (callback) == "function") {
          callback(true, resData);
        }
      },
      fail: function (info) {
        console.log('error in getRegeo:', info)
        // if(Number(info.errCode) == 10001){
        //   util.tips('很抱歉，key不正确或过期');
        // }else if(Number(info.errCode) == 10002){
        //   util.tips('很抱歉，没有权限使用相应的服务');
        // }else if(Number(info.errCode) == 10009){
        //   util.tips('很抱歉，请求key与绑定平台不符');
        // }else if(Number(info.errCode) == 10012){
        //   util.tips('权限不足，服务请求被拒绝');
        // }
        if (callback && typeof (callback) == "function") {
          callback(false, info);
        }
      }
    });
  },
  /**初始化自定义导航 */
  initTabBar:function(index){
    let that = this;
    let num = storage.get('barBadge');
    let pages = getCurrentPages();
    let curPage = pages[pages.length-1];
    let curPath = curPage.__route__;
    if(curPath.indexOf('/')!=0){
      curPath = '/'+curPath;
    }
    let tabBar = this.globalData.tabBar;
    tabBar.color = api.titleColor;
    for(let i = 0 ; i < tabBar.list.length ; i++){
      tabBar.list[i].active = false;
      if(tabBar.list[i].index == index){
        tabBar.list[i].active = true;
      }
      if(tabBar.list[i].keyword == 'cart'){
        tabBar.list[i].badge = num;
        that.dns.cartNum = tabBar.list[i].index;
      }else if(tabBar.list[i].keyword == 'center'){
        that.dns.centerNum = tabBar.list[i].index;
      }
    }
    curPage.setData({
      tabBar:tabBar
    })
  },
  /**设置自定义导航角标 */
  setTabBarBadge:function(num){
    let that = this;
    storage.put('barBadge',num)
    let pages = getCurrentPages();
    let curPage = pages[pages.length-1];
    let curPath = curPage.__route__;
    if(curPath.indexOf('/')!=0){
      curPath = '/'+curPath;
    }
    let tabBar = this.globalData.tabBar;
    if (tabBar && tabBar.list && tabBar.list.length > 0) {
      for(let i = 0 ; i < tabBar.list.length ; i++){
        if(tabBar.list[i].keyword == 'cart'){
          tabBar.list[i].badge = num;
          that.dns.cartNum = tabBar.list[i].index;
        }else if(tabBar.list[i].keyword == 'center'){
          that.dns.centerNum = tabBar.list[i].index;
        }
        tabBar.list[i].active = false;
        if(tabBar.list[i].pagePath == curPath){
          tabBar.list[i].active = true;
        }
      }
    }
    curPage.setData({
      tabBar:tabBar
    })
  },
  getTabBarindex:function(){
    var tabindex = getStorageSync('tabindex');
    if (tabindex == undefined || tabindex == null || tabindex < 0) {
      tabindex = 0;
    }else if(this.globalData.tabBar.list && tabindex > this.globalData.tabBar.list.length - 1){
      tabindex = this.globalData.tabBar.list.length - 1;
    }
    return tabindex;
  },
  onChangeTabBar:function(e){
    var tabindex = e.currentTarget.dataset.index;
    var type = e.currentTarget.dataset.type;
    var url = e.currentTarget.dataset.url;
    var param = e.currentTarget.dataset.param;
    var fastId = e.currentTarget.dataset.fast;
    var cid = e.currentTarget.dataset.cid;
    this.dns.cid = cid || 0; 
    if(fastId){
      setStorageSync('tabcurrent', fastId);
    }
    if(type == 2){
      wx.navigateTo({
        url: url
      })
    }else if(type == 1){
      setStorageSync('tabindex', tabindex);
      wx.switchTab({
        url: url
      })
    }else if(type == 3){
      wx.navigateTo({
        url: url+'?'+param,
      })
    }else if(type == 4 && url == 'scan'){
      //打开扫码
      wx.scanCode({
        success: (res) => {
          this.globalData.product_list.index_search_keyword = res.result;
          router.navigate({
            path: "productList"
          });
        }
      })
    }
  },
  globalData: {
    advertNum:0,
    visitTimer:null,
    flag:false,
    isIphoneX:false,//适配
    product_list: {
      index_search_keyword: "", //搜索关键词
      rule_id: -1, //促销id
      cid: 0, //目录id
      bid: 0, //品牌id
      tag_id: 0, //标签id
      typeId: 0,
      ikcqr : ''
    },
    index: {
      isReload: false //是否重新加载
    },
    location:{
      adcode:"",
      area:"",
      province:"",
      city:"",
      detailAddress:""
    },
    indexShowDialog:false,   //首页是否显示浮层（预览模式）
    defaultTabBars:[
      {
        selectIcon:'icon-a-xingzhuang5kaobei1',
        icon:'icon-shouye',
        text:'首页',
        pagePath:'/pages/index',
        type:1,
        index:0
      },
      {
        selectIcon:'icon-a-xingzhuang6kaobei3',
        icon:'icon-pinlei',
        text:'分类',
        pagePath:'/pages/store/purchase/classify/classify',
        type:1,
        index:1
      },
      {
        selectIcon:'icon-a-xingzhuang18kaobei',
        icon:'icon-kuaisuxiadan',
        text:'快速下单',
        pagePath:'/pages/store/purchase/fast/fast',
        type:1,
        index:2
      },
      {
        selectIcon:'icon-a-xingzhuang11kaobei2',
        icon:'icon-jinhuoche',
        text:'购物车',
        pagePath:'/pages/store/purchase/cart/cart',
        type:1,
        index:3,
        keyword:'cart'
      },
      {
        selectIcon:'icon-a-xingzhuang572kaobei',
        icon:'icon-wode',
        text:'我的',
        pagePath:'/pages/store/profile/index',
        type:1,
        index:4
      }
    ],
    tabBar:{
      color: '#333',
      selectedColor: '#e56b14',
      borderStyle: 'black',
      list: [],
      originList: [], // 底部导航原始数据
      list: []
    },
    fontSizeScale: 1, // 全局字体缩放比例
    appLaunchData: {}, // app onLaunch时的data
    appShowData: {}, // app onShow时的data
    logRequestLevel: 1, // 是否打印接口请求返回值
    pageRefresher: { // 页面是否需要刷新
      fast: false, // 快速下单页面
      classify: false, // 分类页面
      orderList: false, // 订单列表
    },
    receiveOrderHistory: [], // 已收货订单oddnumber列表(用于记录微信确认收货组件成功后,已调用原收货接口的订单)
  },
  /**
   * 系统全局域名解析信息  fkFlag: 3,fkId: 1 ：通用
   */
  dns: {
    proprietor: 2,
    proprietorId: 0,//0,
    fkWay: 2,
    fkFlag: 3,  //0
    fkId: 1, //0
    zoneId: 1,
    cid: 0,
    cartNum: 3,
    centerNum: 4,
    projectDir: '' //线路
  }
})